package main

import (
	"fmt"
	"log"
	"net"
)

func main() {
	udpConn, err := net.ListenUDP("udp", &net.UDPAddr{
		Port: 20000,
	})
	if err != nil {
		log.Fatalln("监听端口失败", err)
		return
	}
	defer udpConn.Close()
	for {
		b := make([]byte, 1024)
		n, addr, err := udpConn.ReadFromUDP(b)
		if err != nil {
			fmt.Println("从udp读取数据失败", err)
			continue
		}
		requestData := string(b[0:n])
		fmt.Printf("发送方的IP地址是:%s,端口是:%d,数据的长度为:%d个字节,内容为:%s \n", addr.IP.String(), addr.Port, n, requestData)

		responseData := fmt.Sprintf("我收到了你的消息,长度为:%d", n)
		_, err = udpConn.WriteToUDP([]byte(responseData), addr)
		if err != nil {
			fmt.Println("返回消息失败", err)
			continue
		}
	}
}
